import {Controller} from "../type/interfaces.ts";
import { handle } from "../vendor/handle.ts";
import {IpcMainEvent, Menu, MenuItem, MenuItemConstructorOptions, shell} from "electron";
import { WORKSPACE } from "../type/const-d.ts";
import {electronStore} from "../vendor/electron-store.js";
import {searchSession} from "../service/search-session.js";
import { machineId } from "node-machine-id";
import { nanoid } from "nanoid";
const template: Array<MenuItemConstructorOptions | MenuItem> = [
  {
    label: "复制",
    role: "copy",
  },
  {
    label: "粘贴",
    role: "paste",
  },
];
const menu = Menu.buildFromTemplate(template);

export default class HomeController implements Controller {

  @handle()
  openWorkspace(){
    shell.openPath(WORKSPACE);
  }

  @handle()
  async openUrl(e: IpcMainEvent, url: string) {
    await shell.openExternal(url);
  }

  @handle()
  async showMenu() {
    menu.popup();
  }

  @handle()
  async saveConfig(e: IpcMainEvent, data: any) {

    if (electronStore.store.proxyUrl != data.proxyUrl || electronStore.store.useProxy != data.useProxy) {
      electronStore.set("useProxy", data.useProxy)
      electronStore.set("proxyUrl", data.proxyUrl)
      searchSession.setProxy(data.useProxy, data.proxyUrl)
    }

  }

  @handle()
  async getConfig() {

  }


  @handle()
  async getMachineId() {
    try {
      const id = electronStore.get("machineId");
      if (id) return id;
      const newId = await machineId();
      electronStore.set("machineId", newId);
      return newId;
    } catch (e) {
      const id = electronStore.get("machineId");
      if (id) return id;
      const newId = nanoid();
      electronStore.set("machineId", newId);
      return newId;
    }
  }

  @handle()
  async getOsInfo() {
    return `${process.platform} ${process.arch} ${process.getSystemVersion()}`
  }
}

export const homeController = new HomeController()
